package com.thinkTank.oa.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.service.DictiontryService;

/**
 * 数据字典controller
 * @author 董力
 * 2018-08-13
 */
@Controller
@RequestMapping("/dictiontry")
public class DictiontryController extends BaseController{
	
	@Resource
	private DictiontryService dictiontryService;

	/*日志输出*/
	private final Logger logger = LoggerFactory.getLogger(PersonController.class);
	
	/**
	 * 分页查询
	 * @param dictiontry
	 * @param model
	 * @return
	 */
	@RequestMapping("/findDictiontryList")
	public String findDictiontryList(@RequestParam(defaultValue="1") Integer pageNo, Dictiontry dictiontry, Model model){
		String groupName = dictiontry.getGroupName();
		Map<String, List<Dictiontry>> dicMap = SystemGlobals.getInstance().getDictiontryMap();
		List<Dictiontry> dicList = new ArrayList<>();
		if (StringUtil.isEmpty(groupName)) 
			dicMap.forEach((key, value) -> dicList.addAll(value));
		else
			dicList.addAll(dicMap.get(groupName));
		if (StringUtil.isNotEmpty(dictiontry.getWorth())) {
			List<Dictiontry> searchList = dicList.stream().filter(dic -> dic.getWorth().equals(dictiontry.getWorth())).collect(Collectors.toList());
			dicList.clear();
			dicList.addAll(searchList);
		}
		Page<Dictiontry> page = PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT, false);
		int endRow = page.getEndRow() > dicList.size() ? dicList.size() : page.getEndRow();
		List<Dictiontry> subList = dicList.subList(page.getStartRow(), endRow);
		page.setTotal(dicList.size());
		PageInfo<Dictiontry> pageInfo = page.toPageInfo();
		pageInfo.setList(subList);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("groupNames", dicMap.keySet());
		return "dictiontry";
	}
	
	/**
	 * 进入添加页面
	 * @return
	 */
	@RequestMapping("/addView")
	public String addView(Dictiontry dictiontry){
		return "dictiontryAdd";
	}
	
	/**
	 * 添加
	 * @param dictiontry
	 * @return
	 */
	@RequestMapping("/addDictiontry")
	public String addDictiontry(@Valid Dictiontry dictiontry, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
            //出错时将填写的值返回
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return addView(dictiontry);
        }
		
		Map<String, List<Dictiontry>> dicMap = SystemGlobals.getInstance().getDictiontryMap();
		String groupName = dictiontry.getGroupName();
		List<Dictiontry> dicList = dicMap.get(groupName);
		int sort = 1;
		if (dicList != null && !dicList.isEmpty()) {
			boolean eqNames = dicList.stream().map(Dictiontry::getNames).filter(StringUtil::isNotEmpty).anyMatch(names -> names.equals(dictiontry.getNames()));
			boolean eqWorth = dicList.stream().map(Dictiontry::getWorth).filter(StringUtil::isNotEmpty).anyMatch(worth -> worth.equals(dictiontry.getWorth()));
			model.addAttribute("eqNames", eqNames ? "同一个组中已经存在相同的names" : "");
			model.addAttribute("eqWorth", eqWorth ? "同一个组中已经存在相同的值" : "");
			if (eqNames || eqWorth)
				return addView(dictiontry);
			sort = dicList.stream().map(Dictiontry::getSort).filter(s -> s != null).max(Comparator.comparing(Function.identity())).orElse(0) + 1;
		}
		dictiontry.setSort(sort);
		dictiontryService.add(dictiontry);
		//更新缓存
		dicMap.merge(groupName, new ArrayList<>(), (oldList, list) -> oldList).add(dictiontry);
		String encode = encode(dictiontry.getWorth());
		return "redirect:/dictiontry/findDictiontryList?groupName="+dictiontry.getGroupName()+"&worth="+encode;
	}
	
	/**
	 * 进入修改页面
	 * @author dongli
	 * @date 2018年8月21日
	 * @param pid
	 * @param model
	 * @return
	 */
	@RequestMapping("/updateView")
	public String updateView(Dictiontry dictiontry){
		return "dictiontryUpdate";
	}
	
	/**
	 * 修改
	 * @author dongli
	 * @date 2018年8月21日
	 * @param dictiontry
	 * @param worth
	 * @return
	 */
	@RequestMapping("/updateDictiontry")
	public String updateDictiontry(@Valid Dictiontry dictiontry, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
            //出错时将填写的值返回
            List<FieldError> list = bindingResult.getFieldErrors();
            list.forEach(e -> logger.error("错误字段：{}, 错误信息：{}", e.getField(), e.getDefaultMessage()));
            list.forEach(e -> model.addAttribute(e.getField(), e.getDefaultMessage()));
            return addView(dictiontry);
        }
		//通过pid修改值
		dictiontryService.update(dictiontry);
		//更新缓存
		List<Dictiontry> dicList = getDicList(dictiontry.getGroupName());
		dicList.stream().filter(dic -> dic.getPid().equals(dictiontry.getPid())).findAny().get().setWorth(dictiontry.getWorth());
		String encode = encode(dictiontry.getWorth());
		return "redirect:/dictiontry/findDictiontryList?groupName="+dictiontry.getGroupName()+"&worth="+encode;
	}

	/**
	 * 转换成utf-8编码
	 * @author pdz
	 * @date 2018年12月11日
	 * @param needEncode
	 * @return
	 */
	private String encode(String needEncode) {
		String encode = null;
		try {
			encode = URLEncoder.encode(needEncode, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encode;
	}
	
	
	
}
